<template>
  <div class="category-management-container">
    <!-- 搜索区域（移除了推荐类型筛选） -->
    <div class="search-area">
      <el-form
        :model="searchForm"
        :inline="true"
        class="search-form"
      >
        <el-form-item label="分类ID">
          <el-input
            v-model="searchForm.id"
            placeholder="请输入分类ID"
            clearable
            style="width: 150px"
          />
        </el-form-item>

        <el-form-item label="分类名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入分类名称"
            clearable
            style="width: 150px"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleSearch"
          >
            查询
          </el-button>
          <el-button @click="resetSearch">
            重置
          </el-button>
          <el-button
            type="danger"
            :disabled="selectedIds.length === 0"
            @click="batchDelete"
          >
            批量删除({{ selectedIds.length }})
          </el-button>
          <el-button
            type="success"
            @click="handleAdd"
          >
            新增分类
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域（移除了是否推荐列） -->
    <div class="table-container">
      <el-table
        :data="currentPageData"
        border
        style="width: 100%; margin-top: 20px"
        :header-cell-style="{
          background: '#f5f7fa',
          color: '#606266',
          fontWeight: 'bold'
        }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        />
        <el-table-column
          prop="id"
          label="分类ID"
          width="120"
          align="center"
        />
        <el-table-column
          prop="name"
          label="分类名称"
          align="center"
        />
        <el-table-column
          prop="description"
          label="分类描述"
          align="center"
        />
        <el-table-column
          prop="createTime"
          label="创建时间"
          align="center"
          width="180"
        />
        <el-table-column
          label="图片"
          align="center"
          width="150"
        >
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.image"
              style="width: 60px; height: 60px"
              :src="scope.row.image"
              :preview-src-list="[scope.row.image]"
              fit="cover"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="220"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)"
            >
              修改
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域（保持不变） -->
    <div class="pagination-area">
      <span>共 {{ filteredCategoryList.length }} 条</span>
      <el-select
        v-model="pagination.pageSize"
        size="mini"
        style="width: 100px; margin: 0 15px"
        @change="handleSizeChange"
      >
        <el-option
          v-for="item in [10, 20, 50]"
          :key="item"
          :label="`${item}条/页`"
          :value="item"
        />
      </el-select>
      <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        layout="prev, pager, next, jumper"
        :total="filteredCategoryList.length"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框（移除了是否推荐开关） -->
    <el-dialog
      :title="dialogType === 'add' ? '新增分类' : '修改分类'"
      :visible.sync="dialogVisible"
      width="500px"
      :modal="false"
    >
      <el-form
        ref="categoryForm"
        :model="currentCategory"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item
          label="分类名称"
          prop="name"
        >
          <el-input v-model="currentCategory.name" />
        </el-form-item>
        <el-form-item label="分类描述">
          <el-input
            v-model="currentCategory.description"
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="分类图片">
          <el-upload
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <el-button
              size="small"
              type="primary"
            >
              点击上传
            </el-button>
            <div class="el-upload__tip">
              只能上传jpg/png文件，且不超过2MB
            </div>
          </el-upload>
          <div
            v-if="currentCategory.image"
            class="image-preview"
          >
            <el-image
              style="width: 100px; height: 100px; margin-top: 10px"
              :src="currentCategory.image"
              :preview-src-list="[currentCategory.image]"
              fit="cover"
            />
            <el-button
              size="mini"
              type="danger"
              plain
              style="margin-top: 5px"
              @click="removeImage"
            >
              移除图片
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="confirmSubmit"
        >
          保存
        </el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框（移除了是否推荐显示） -->
    <el-dialog
      title="分类详情"
      :visible.sync="detailDialogVisible"
      width="500px"
      :modal="false"
    >
      <el-descriptions
        :column="1"
        border
      >
        <el-descriptions-item label="分类ID">
          {{ currentCategory.id }}
        </el-descriptions-item>
        <el-descriptions-item label="分类名称">
          {{ currentCategory.name }}
        </el-descriptions-item>
        <el-descriptions-item label="分类描述">
          {{ currentCategory.description || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ currentCategory.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="分类图片">
          <el-image
            v-if="currentCategory.image"
            style="width: 200px; height: 200px"
            :src="currentCategory.image"
            :preview-src-list="[currentCategory.image]"
            fit="cover"
          />
          <span v-else>无图片</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CategoryManagement',
  data () {
    return {
      searchForm: {
        id: '',
        name: ''
      },
      selectedIds: [],
      dialogVisible: false,
      detailDialogVisible: false,
      dialogType: 'add',
      pagination: {
        currentPage: 1,
        pageSize: 10
      },
      currentCategory: {
        id: null,
        name: '',
        description: '',
        image: '',
        createTime: '',
        tempImage: null
      },
      formRules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      },
      categoryList: [
        {
          id: 1,
          name: '校园',
          description: '校园生活相关内容分类，包括学习、社团活动等',
          image: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
          createTime: '2023-05-10 14:30:22'
        },
        {
          id: 2,
          name: '音乐',
          description: '各种音乐类型和音乐人介绍',
          image: 'https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg',
          createTime: '2023-05-11 09:15:45'
        }
        // ...其他分类数据（移除了recommended字段）
      ],
      filteredResults: []
    }
  },
  computed: {
    filteredCategoryList () {
      return this.categoryList.filter(item => {
        if (this.searchForm.id && !item.id.toString().includes(this.searchForm.id)) {
          return false
        }
        if (this.searchForm.name && !item.name.includes(this.searchForm.name)) {
          return false
        }
        return true
      })
    },
    currentPageData () {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const end = start + this.pagination.pageSize
      return this.filteredResults.slice(start, end)
    }
  },
  created () {
    this.filteredResults = [...this.categoryList]
  },
  methods: {
    handleSearch () {
      this.pagination.currentPage = 1
      this.filteredResults = this.categoryList.filter(item => {
        if (this.searchForm.id && !item.id.toString().includes(this.searchForm.id)) {
          return false
        }
        if (this.searchForm.name && !item.name.includes(this.searchForm.name)) {
          return false
        }
        return true
      })
    },
    resetSearch () {
      this.searchForm = {
        id: '',
        name: ''
      }
      this.pagination.currentPage = 1
      this.filteredResults = [...this.categoryList]
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
    },
    handleCurrentChange (val) {
      this.pagination.currentPage = val
    },
    handleSelectionChange (selection) {
      this.selectedIds = selection.map(item => item.id)
    },
    handleAdd () {
      this.dialogType = 'add'
      this.currentCategory = {
        id: null,
        name: '',
        description: '',
        image: '',
        createTime: new Date().toLocaleString(),
        tempImage: null
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.categoryForm) {
          this.$refs.categoryForm.clearValidate()
        }
      })
    },
    handleEdit (row) {
      this.dialogType = 'edit'
      this.currentCategory = {
        ...row,
        tempImage: null
      }
      this.dialogVisible = true
    },
    handleDetail (row) {
      this.currentCategory = { ...row }
      this.detailDialogVisible = true
    },
    handleDelete (id) {
      this.$confirm('确定删除该分类吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.categoryList = this.categoryList.filter(item => item.id !== id)
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    batchDelete () {
      this.$confirm('确定删除选中的分类吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.categoryList = this.categoryList.filter(item => !this.selectedIds.includes(item.id))
        this.selectedIds = []
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    confirmSubmit () {
      this.$refs.categoryForm.validate(valid => {
        if (valid) {
          if (this.currentCategory.tempImage) {
            setTimeout(() => {
              this.processFormSubmit()
            }, 500)
          } else {
            this.processFormSubmit()
          }
        }
      })
    },
    processFormSubmit () {
      if (this.dialogType === 'add') {
        const newId = this.categoryList.length > 0
          ? Math.max(...this.categoryList.map(item => item.id)) + 1
          : 1

        const newCategory = {
          id: newId,
          name: this.currentCategory.name,
          description: this.currentCategory.description,
          image: this.currentCategory.image || '',
          createTime: new Date().toLocaleString()
        }

        this.categoryList.push(newCategory)
        this.filteredResults.push(newCategory)
        this.$message.success('新增成功')
      } else {
        const index = this.categoryList.findIndex(item => item.id === this.currentCategory.id)
        if (index !== -1) {
          const updatedCategory = {
            ...this.currentCategory,
            image: this.currentCategory.image || this.categoryList[index].image
          }

          this.categoryList.splice(index, 1, updatedCategory)
          const filteredIndex = this.filteredResults.findIndex(item => item.id === this.currentCategory.id)
          if (filteredIndex !== -1) {
            this.filteredResults.splice(filteredIndex, 1, updatedCategory)
          }
          this.$message.success('修改成功')
        }
      }
      this.dialogVisible = false
    },
    handleUploadSuccess (response, file) {
      this.currentCategory.tempImage = {
        raw: file.raw,
        preview: URL.createObjectURL(file.raw)
      }
      this.currentCategory.image = this.currentCategory.tempImage.preview
    },
    beforeUpload (file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传JPG/PNG格式的图片!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过2MB!')
      }
      return isImage && isLt2M
    },
    removeImage () {
      this.currentCategory.image = ''
      this.currentCategory.tempImage = null
    }
  }
}
</script>

<style scoped>
/* 样式保持不变 */
.category-management-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 15px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.pagination-area .el-pagination {
  margin-left: 15px;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.image-preview {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }

  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
  }

  .search-form .el-form-item .el-input {
    width: 100% !important;
  }

  .pagination-area {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
